package com.ruoyi.core.task;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.RedisCacheKeyHelper;
import com.ruoyi.core.domain.ClientProductUser;
import com.ruoyi.core.mapper.ServerConfigMapper;
import com.ruoyi.core.vo.CookieRefresh;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Company: 北京卡拉卡尔股份技术有限公司
 * @Author: Darren Ho
 * @Date: 11/6/2020 18:07
 */

@Component
public class MerchantWordCookieRefreshOnOffUpdateJob implements InitializingBean, CookieRefreshTPeriodicTriggerJob {

    private final Logger logger = LoggerFactory.getLogger(MerchantWordCookieRefreshOnOffUpdateJob.class);


    private Integer cookieRefreshTimeInterval;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public void start(List<ClientProductUser> clientProductUsers) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("merchant word cookie  on-off  refresh  begin {} ",simpleDateFormat.format(new Date()));
        if ((clientProductUsers != null && !clientProductUsers.isEmpty())) {
            clientProductUsers.forEach(item -> {
                String key = RedisCacheKeyHelper.getMerchantWordCookieRefreshOnOffKey(item.getId());
                redisCache.setCacheObject(key, CookieRefresh.ON, 2, TimeUnit.MINUTES);
            });
        }
    }

    @Override
    public Integer getCookieRefreshTimeInterval() {
        return this.cookieRefreshTimeInterval;
    }

    @Override
    public void setCookieRefreshTimeInterval(Integer cookieRefreshTimeInterval) {
        this.cookieRefreshTimeInterval = cookieRefreshTimeInterval;
        logger.info("update merchant word  cookie refresh time interval :[{}]", cookieRefreshTimeInterval);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        // 初始化 各个网站定时任务配置
        int cookieRefreshTimeIntervalInter = 30;

        String cookieRefreshTimeInterval = sysConfigService.selectConfigByKey("COOKIE_REFRESH_TIME_INTERVAL");

        if (!StringUtils.hasText(cookieRefreshTimeInterval)) {
            SysConfig sysConfig = new SysConfig();
            sysConfig.setConfigKey("COOKIE_REFRESH_TIME_INTERVAL");
            sysConfig.setConfigValue(String.valueOf(cookieRefreshTimeIntervalInter));
            sysConfig.setConfigName("cookie刷新开关定时更新时间配置项");
            sysConfig.setCreateBy("admin");
            sysConfig.setConfigType("Y");
            sysConfigService.insertConfig(sysConfig);
        } else {
            cookieRefreshTimeIntervalInter = Integer.parseInt(cookieRefreshTimeInterval);
        }
        setCookieRefreshTimeInterval(cookieRefreshTimeIntervalInter);
    }

    public void startRightNow(List<ClientProductUser> clientProductUsers) {
        logger.info("merchant word cookie  on-off  refresh  right now  ");
        if ((clientProductUsers != null && !clientProductUsers.isEmpty())) {
            clientProductUsers.forEach(item -> {

                String productUserLoginTimeKey = getProductUserLoginTimeKey(item.getId());

                String productUser2ProductConcurrentLockKey = RedisCacheKeyHelper.getProductUser2ProductConcurrentLockKey(item.getId(), item.getProductId());

                redisCache.deleteObject(Arrays.asList(productUserLoginTimeKey, productUser2ProductConcurrentLockKey));

                String key = RedisCacheKeyHelper.getMerchantWordCookieRefreshOnOffKey(item.getId());
                redisCache.setCacheObject(key, CookieRefresh.ON, 2, TimeUnit.MINUTES);
            });

        }

    }

    private String getProductUserLoginTimeKey(Long productUserId) {

        String result = "productUserLoginTimeKeyPrefix";
        String productUserLoginTimeKeyPrefix = RedisCacheKeyHelper.getProductUserLoginTimeKeyPrefix(productUserId);
        Collection<String> keys = redisCache.keys(productUserLoginTimeKeyPrefix + "*");
        if (keys != null && !keys.isEmpty()) {
            result = keys.iterator().next();
        }
        return result;
    }
}
